#include "AliIoTControl.h"
#include <AliyunIoTSDK.h>
#include "FishControl.h"

#define PRODUCT_KEY "a1t8LbH35EZ"
#ifndef DEVICE_NAME
#define DEVICE_NAME "Y09Fv9zVryIzMJSmU719"
#endif
#ifndef DEVICE_SECRET
#define DEVICE_SECRET "3ccad683a3f947cf67e1c3741ba42c80"
#endif
#define REGION_ID "cn-shanghai"

AliIoTControl::AliIoTControl(): ready(false)
{
}

AliIoTControl::~AliIoTControl()
{
    ready = false;
}

void AliIoTControl::begin()
{
    AliyunIoTSDK::begin(aliClient, PRODUCT_KEY, DEVICE_NAME, DEVICE_SECRET, REGION_ID);
    AliyunIoTSDK::bindData("PowerSwitch", std::bind(&AliIoTControl::powerOnChange, this, std::placeholders::_1));
    AliyunIoTSDK::bindData("colorTemperature", std::bind(&AliIoTControl::lampTypeOnChange, this, std::placeholders::_1));
    AliyunIoTSDK::bindData("brightness", std::bind(&AliIoTControl::brightnesspeOnChange, this, std::placeholders::_1));

    ready = true;
}

void AliIoTControl::loop()
{
    AliyunIoTSDK::loop();
}

void AliIoTControl::updateStatus()
{
    AliyunIoTSDK::send((char*)PSTR("PowerSwitch"), (fishCtrl.getLamp() == FishControl::OFF) ? 0: 1);
    AliyunIoTSDK::send((char*)PSTR("colorTemperature"), fishCtrl.getLamp());
    int32_t brigtness = fishCtrl.getBrightness() *100 /1023;
    AliyunIoTSDK::send((char*)PSTR("brightness"), brigtness);
    AliyunIoTSDK::flush();
}

void AliIoTControl::powerOnChange(JsonVariant ele)
{
    int onOff = ele["PowerSwitch"];
    if (onOff == 1)
    {
        fishCtrl.switchOnLamp(true);
    }
    else
    {
        fishCtrl.switchOnLamp(false);
    }
}

void AliIoTControl::lampTypeOnChange(JsonVariant ele)
{
    int idx = ele["colorTemperature"];
    fishCtrl.setLamp(idx, true);
}

void AliIoTControl::brightnesspeOnChange(JsonVariant ele)
{
    int32_t idx = ele["brightness"];
    int32_t brigtness = 1023 * idx / 100;
    fishCtrl.setBrightness(brigtness);
}